<script>
import {
  getPresentInfoByParkspaceCode,
  getFee,
  outSettle,
  GetPosConfig,
  appfile,
} from "@/api/modules/home";
import { Toast } from "vant";

import {
  getPresentDetail,
  appOrder,
  paySuccess,
  // addImage,
} from "@/api/modules/order";
import axios from "axios";

export default {
  computed: {
    userInfo() {
      return this.$store.getters.userInfoGetter;
    },
  },
  data() {
    return {
      showPopover: false,
      actions: [
        {
          text: "打印小票",
          value: 1,
        },
        {
          text: "查看图片",
          value: 2,
        },
        // {
        //   text: "补拍照片",
        //   value: 3,
        // },
        {
          text: "预支付",
          value: 4,
        },
      ],
      loadData: {},
      loadDataFee: {},
      show: false,
      cardList: ["小", "中", "大", "新", "特"],
      params: {},
      payType: 1,
      qrData: {},
      showQr: false,
      settlementShow: false,
      imgList: [],
      loading: false,
      loading2: false,
      inTicketConfig: {},
      params2: {
        payMoney: "",
        freeMoney: 0,
        orderType: 1,
        totalMoney: "",
        originRecordId: "",
      },
    };
  },
  async mounted() {
    const toast = Toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: "加载中",
    });
    await this.getIninFn();
    await this.getIninFeeFn();
    this.getAppfile();
    this.getGetPosConfig();
    toast.clear();
  },
  methods: {
    async afterRead() {
      // eslint-disable-next-line no-undef
      window.android.goCameraActivity();
      // 此时可以自行将文件上传至服务器
    },

    async showBitmapBase64(file) {
      Toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true,
        message: "上传中...",
      });
      this.loading = true;
      let obj = {};
      obj.data = file;
      obj.packageName = `image/app/${this.userInfo.parkCode}/${this.$route.query.roadCode}`;
      axios
        .post(
          `${process.env.VUE_APP_UPLOAD_URL}/file/manage/upload/base64`,
          obj
        )
        .then((res) => {
          if (res.data.code === 200) {
            this.getAppfile();
          }
          Toast.clear();
        })
        .catch(() => {
          Toast.clear();
        });
    },
    onSelect(row) {
      if (row.value === 1) {
        this.getDayinInitFn();
      } else if (row.value === 2) {
        this.ImagePreviewFn();
      } else if (row.value === 3) {
        this.afterRead();
      } else if (row.value === 4) {
        this.$router.push({
          path: "/payCar",
          query: {
            id: this.loadDataFee.parkingRecordId,
            type: "details",
          },
        });
      }
    },
    async settlementInitFn() {
      if (this.loadDataFee.totalFee == this.loadDataFee.totalActualBalance) {
        await outSettle({
          ...this.$route.query,
          ...this.loadDataFee,
          tollmanId: this.userInfo.id,
          isPayEscape: 0,
        });
        // await paySuccess({
        //   orderNo: row.orderNo,
        //   payTime: this.$utils.filterTimeFn(new Date().getTime()),
        // });
        Toast("结算成功");
        setTimeout(() => {
          this.$router.replace("/home");
        }, 500);
        return;
      }
      this.settlementShow = true;
    },
    async settlementShowChange() {
      if (this.loadDataFee.totalActualBalance >= this.loadDataFee.totalFee) {
        this.$router.push({
          path: "/moneyChange",
          query: {
            parkingRecordId: this.loadData.parkingRecordId,
            money: (
              (this.loadDataFee.totalActualBalance -
                this.loadDataFee.totalFee) /
              100
            ).toFixed(2),
            ...this.$route.query,
            ...this.loadDataFee,
            isPayEscape: 0,
          },
        });
        return;
      } else {
        this.show = true;
      }
    },
    async getAppfile() {
      const { code, data } = await appfile({
        ...this.$route.query,
        fileType: "0",
      });
      if (code === 200) {
        this.imgList = data;
      }
    },
    ImagePreviewFn() {
      this.$router.push({
        path: "/ImagePreview",
        query: {
          ...this.$route.query,
        },
      });
    },
    async confirm() {
      if (this.payType === 1) {
        const toast1 = Toast.loading({
          duration: 0, // 持续展示 toast
          forbidClick: true,
          message: "结算中",
        });

        let form = {
          ...this.params2,
          freeMoney: this.params2.freeMoney * 100,
          payMoney: this.params2.payMoney - this.params2.freeMoney * 100,
        };

        const data1 = await appOrder({
          details: [form],
          ...this.$route.query,
          payType: 0,
          payChannel: 1,
          tollmanId: this.userInfo.id || "1647546075499859970",
        });
        await paySuccess({
          orderNo: data1.data.orderNo,
          payTime: this.$utils.filterTimeFn(new Date().getTime()),
        });

        const { code, data } = await outSettle({
          ...this.$route.query,
          ...this.loadDataFee,
          tollmanId: this.userInfo.id,
          isPayEscape: 1,
        });
        if (code === 200 && data) {
          Toast("结算成功");
          toast1.clear();
          setTimeout(() => {
            this.$router.replace("/home");
          }, 500);
        }
      } else {
        this.showQr = true;
        this.getGetPosConfig();
      }
    },

    async confirmQr() {
      let form = {
        ...this.params2,
        freeMoney: this.params2.freeMoney * 100,
        payMoney: this.params2.payMoney - this.params2.freeMoney * 100,
      };

      const data1 = await appOrder({
        details: [form],
        ...this.$route.query,
        payType: 0,
        payChannel: 1,
        tollmanId: this.userInfo.id || "1647546075499859970",
      });
      await paySuccess({
        orderNo: data1.data.orderNo,
        payTime: this.$utils.filterTimeFn(new Date().getTime()),
      });

      const { code, data } = await outSettle({
        ...this.$route.query,
        ...this.loadDataFee,
        tollmanId: this.userInfo.id,
        isPayEscape: 1,
      });
      if (code === 200 && data) {
        Toast("结算成功");
        setTimeout(() => {
          this.$router.replace("/home");
        }, 500);
      }
    },
    async getGetPosConfig() {
      const { code, data } = await GetPosConfig({});
      if (code === 200) {
        this.qrData = data;

        this.inTicketConfig = {
          ...JSON.parse(data.inTicketConfig),
          payTicketQrCode: data.payTicketQrCode,
        };
      }
    },
    async getIninFeeFn() {
      this.loading2 = true;
      const { code, data } = await getFee({
        ...this.$route.query,
      });
      this.loading2 = false;
      if (code === 200 && data) {
        this.loadDataFee = data;
        this.params2.totalMoney = data.totalFee;
        this.params2.payMoney = data.totalFee - data.totalActualBalance;
      }
    },
    async getIninFn() {
      this.loading = true;
      const { code, data } = await getPresentInfoByParkspaceCode({
        ...this.$route.query,
      });
      this.loading = false;
      if (code === 200 && data) {
        this.loadData = data;
        this.loadData.inCarTime =
          new Date().getTime() - data.parkTime * 60 * 1000;

        this.params2.originRecordId = data.parkingRecordId;
      }
    },

    async getDayinInitFn() {
      this.loading = true;
      const { code, data } = await getPresentDetail({
        parkingRecordId: this.loadDataFee.parkingRecordId,
        tollmanId: this.userInfo.id || "1647546075499859970",
      });
      this.loading = false;
      if (code === 200) {
        let params = {};
        params.title = this.inTicketConfig.title;
        params.message = this.inTicketConfig.message;
        if (this.inTicketConfig.isTollman) {
          params["收费员"] = this.userInfo.tollmanName;
        }

        if (this.inTicketConfig.isParkCode) {
          params["停车路段"] = data.parkName;
        }

        params["泊车号"] = data.parkspaceCode;
        if (this.inTicketConfig.isCarNum) {
          params["车牌号"] = data.carNo || "无牌车";
        }
        if (this.inTicketConfig.isCarType) {
          params["车辆类型"] = this.$utils.filterOpt(data.carType, "carType");
        }

        if (this.inTicketConfig.isInTime) {
          params["入车时间"] = data.sysTime;
        }

        params.payTicketQrCode = this.inTicketConfig.payTicketQrCode;
        try {
          const str = JSON.stringify(params);
          // eslint-disable-next-line no-undef
          window.android.printTicket(str);
        } catch (e) {
          console.log(e);
        }
      }
    },
  },
};
</script>
<template>
  <div class="carDetails">
    <van-dialog
      confirm-button-color="#06C68A"
      v-model="settlementShow"
      @confirm="settlementShowChange"
      confirm-button-text="确认"
      @cancel="settlementShow = false"
      title="确认进行出车吗"
      show-cancel-button
    >
      <div
        class="dialogList"
        style="
          padding: 20px;
          box-sizing: border-box;
          font-weight: bold;
          font-size: 20px;
        "
      >
        <div>
          出车时间:&nbsp;{{ $utils.filterTimeFn(new Date().getTime()) }}
        </div>
        <div v-if="loadDataFee.totalActualBalance > loadDataFee.totalFee">
          找零金额:&nbsp; ¥{{
            Math.abs(
              (loadDataFee.totalActualBalance - loadDataFee.totalFee) / 100
            ).toFixed(2)
          }}
        </div>
        <div v-else>
          应缴金额:&nbsp; ¥{{
            Math.abs(
              (loadDataFee.totalActualBalance - loadDataFee.totalFee) / 100
            ).toFixed(2)
          }}
        </div>

        <div style="display: flex; align-items: center">
          优惠金额:
          <div>
            <van-stepper :min="0" v-model="params2.freeMoney" />
          </div>
          元
        </div>
      </div>
    </van-dialog>

    <van-dialog
      confirm-button-color="#06C68A"
      v-model="show"
      @confirm="confirm"
      @cancel="show = false"
      title="选择支付方式"
      show-cancel-button
    >
      <div class="dialogList">
        <div
          @click.stop="payType = 1"
          class="dialogList-item"
          :class="{ 'dialogList-item-bg': payType === 1 }"
        >
          <div>
            <van-icon style="margin-right: 10px" name="cash-back-record" />
            现金支付
          </div>
        </div>
        <div
          @click.stop="payType = 2"
          class="dialogList-item"
          :class="{ 'dialogList-item-bg': payType === 2 }"
        >
          <div>
            <van-icon style="margin-right: 10px" name="qr" />
            二维码支付
          </div>
        </div>
      </div>
    </van-dialog>
    <van-dialog
      confirm-button-color="#06C68A"
      v-model="showQr"
      @confirm="confirmQr"
      @cancel="
        showQr = false;
        show = true;
      "
      title="支付二维码"
      confirmButtonText="已支付"
      :show-confirm-button="!!qrData.payTicketQrCode"
      show-cancel-button
    >
      <div
        class="dialogList"
        style="display: flex; justify-content: center; align-items: center"
      >
        <img
          v-if="qrData.payTicketQrCode"
          :src="qrData.payTicketQrCode"
          style="width: 80%"
          alt=""
        />
        <div v-else>请管理员配置收费二维码</div>
      </div>
    </van-dialog>
    <div class="carDetails-head">
      <div class="carDetails-head-left" @click="$router.go(-1)">
        <i class="tc ting-fanhui"></i>
      </div>
      <div class="carDetails-head-center">在场车辆详情</div>
      <van-popover
        v-model="showPopover"
        trigger="click"
        theme="dark"
        placement="bottom-end"
        :actions="actions"
        @select="onSelect"
      >
        <template #reference>
          <div class="carDetails-head-left">
            <i class="tc ting-gengduo1"></i>
          </div>
        </template>
      </van-popover>
    </div>
    <div class="carDetails-car">
      <div class="carDetails-car-top">
        <div class="left">
          <i class="tc ting-dingwei"></i>
          <span>{{ loadData.parkspaceCode }}</span>
        </div>
        <div class="carDetails-car-cont">
          <div class="carDetails-car-cont-left">
            <div>{{ loadData.carNo || "无牌车" }}</div>
            <div class="card">{{ cardList[loadData.carType] }}</div>
            <div class="line line1"></div>
            <div class="line line2"></div>
            <div class="line line3"></div>
            <div class="line line4"></div>
          </div>
          <!--        <div class="carDetails-car-cont-right" @click="ImagePreviewFn">-->
          <!--          <i class="tc ting-tupian"></i>-->
          <!--          <span>查看图片</span>-->
          <!--        </div>-->
        </div>
        <!--        <div class="right" @click="getDayinInitFn">-->
        <!--          <i class="tc ting-dayinji_o"></i>-->
        <!--          <span> 打印小票</span>-->
        <!--        </div>-->
      </div>
    </div>

    <div class="carDetails-money">
      <div class="carDetails-money-name">
        <div class="title">应收金额</div>
        <div class="money">
          ¥ <span>{{ loadDataFee.totalFee / 100 || 0 }}</span>
        </div>
      </div>
      <div class="line"></div>

      <div class="carDetails-money-list">
        <div class="items">
          <div class="title">实收</div>
          <div>¥{{ (loadDataFee.payMoney / 100).toFixed(2) || 0 }}</div>
        </div>
        <!--        <div class="items">-->
        <!--          <div class="title">实收</div>-->
        <!--          <div>¥20</div>-->
        <!--        </div>-->
        <div class="items">
          <div class="title">预支付剩余</div>
          <div>
            ¥{{ (loadDataFee.totalActualBalance / 100).toFixed(2) || 0 }}
          </div>
        </div>
      </div>

      <div class="line"></div>
      <div class="carDetails-money-list">
        <div class="items">
          <div class="title">入车时间</div>
          <div>{{ loadData.inCarTime | filterTime("HH:mm:SS") }}</div>
          <div class="title">
            {{ loadData.inCarTime | filterTime("YYYY-MM-DD") }}
          </div>
        </div>
        <div class="items">
          <div class="title">停车时长</div>
          <div>{{ loadData.parkTime }}分钟</div>
        </div>
      </div>

      <div class="carDetails-money-btn">
        <van-button
          color="linear-gradient(to right, #a7f19e, #06C68A)"
          @click="settlementInitFn"
          size="large"
          >结算离场
        </van-button>
        <div style="margin-top: 20px"></div>
        <van-button
          :loading="loading"
          type="info"
          @click="getDayinInitFn"
          size="large"
          >打印小票
        </van-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.carDetails {
  width: 100%;
  height: 100vh;
  background-image: linear-gradient(180deg, #06c68a, white);

  .carDetails-head {
    width: 100%;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 12px;
    box-sizing: border-box;

    .carDetails-head-left {
      width: 40px;
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 4px;
      margin-top: 10px;

      background: rgba(255, 255, 255, 0.25);

      i {
        color: white;
        font-size: 24px;
        font-weight: bold;
      }
    }

    .carDetails-head-center {
      color: white;
      font-size: 18px;
      font-weight: bold;
    }
  }

  .carDetails-car {
    padding: 20px 12px;
    box-sizing: border-box;

    .carDetails-car-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 20px;
      color: white;

      .left {
        i {
          font-size: 20px;
          font-weight: bold;
          margin-right: 6px;
        }
      }

      .right {
        font-size: 14px;
        border: 1px solid white;
        color: white;
        padding: 3px 10px;
        border-radius: 15px;
      }
    }

    .carDetails-car-cont {
      display: flex;
      align-items: flex-end;
      justify-content: space-between;

      .carDetails-car-cont-left {
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 4px;
        background: rgba(255, 255, 255, 0.25);
        padding: 4px 10px;
        box-sizing: border-box;
        font-size: 25px;
        color: white;
        font-weight: bold;
        position: relative;

        .card {
          background: white;
          color: #606266;
          padding: 0 2px;
          font-size: 14px;
          margin-left: 10px;
          border-radius: 4px;
        }

        .line {
          width: 5px;
          height: 5px;
          border-radius: 5px;
          background: white;
        }

        .line1 {
          position: absolute;
          left: 3px;
          top: 3px;
        }

        .line2 {
          position: absolute;
          right: 3px;
          top: 3px;
        }

        .line3 {
          position: absolute;
          left: 3px;
          bottom: 3px;
        }

        .line4 {
          position: absolute;
          right: 3px;
          bottom: 3px;
        }
      }

      .carDetails-car-cont-right {
        display: flex;
        border: 1px solid white;
        color: white;
        padding: 3px 10px;
        border-radius: 15px;

        i {
          margin-right: 4px;
        }
      }
    }
  }

  .carDetails-money {
    width: calc(100% - 24px);
    padding: 20px 0;
    box-sizing: border-box;
    margin: 0 auto;
    background: white;
    border-radius: 10px;
    box-shadow: 0 8px 20px 0 rgba(0, 0, 0, 0.1);

    .carDetails-money-name {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .title {
        color: #999999;
        font-size: 18px;
      }

      .money {
        font-size: 24px;
        color: #ffa230;
        font-weight: bold;

        span {
          font-size: 40px;
        }
      }
    }

    .line {
      width: 100%;
      height: 2px;
      background: #f3f4f5;
      margin: 20px 0;
    }

    .carDetails-money-list {
      display: flex;
      align-items: center;
      justify-content: space-around;

      .items {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        div {
          font-weight: bold;
          font-size: 20px;
        }

        .title {
          color: darkgrey;
          font-size: 16px;
          font-weight: 400;
        }
      }
    }

    .carDetails-money-btn {
      width: 80%;
      margin: 40px auto 20px auto;
    }
  }

  .dialogList {
    padding: 20px 0;

    .dialogList-item {
      width: 80%;
      margin: 0 auto;
      margin-bottom: 20px;
      background-color: #d8d8d8;
      padding: 10px 20px;
      box-sizing: border-box;
      border-radius: 6px;
      font-weight: bold;

      .van-icon {
        color: #999999;
      }
    }

    .dialogList-item-bg {
      background-color: var(--theme-color);
      color: white;

      .van-icon {
        color: white;
      }
    }
  }
}
</style>
